import axios from 'axios'
import type { LoginForm, RegisterForm, Device, Task } from '../types'

const API_URL = 'http://localhost:3000/api'

const axiosInstance = axios.create({
    baseURL: API_URL,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器：添加token
axiosInstance.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器：处理token过期
axiosInstance.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 401) {
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            window.location.href = '/login'
        }
        return Promise.reject(error)
    }
)

export const authService = {
    async login(data: LoginForm) {
        return axiosInstance.post('/auth/login', data)
    },

    async register(data: RegisterForm) {
        return axiosInstance.post('/auth/register', data)
    },

    async getUserInfo() {
        return axiosInstance.get('/user/profile')
    },

    logout() {
        localStorage.removeItem('token')
        localStorage.removeItem('user')
    }
}

export const deviceService = {
    async getAllDevices() {
        return axiosInstance.get<Device[]>('/devices')
    },

    async addDevice(device: Omit<Device, 'id'>) {
        return axiosInstance.post('/devices', device)
    },

    async updateDevice(id: number, device: Partial<Device>) {
        return axiosInstance.put(`/devices/${id}`, device)
    },

    async deleteDevice(id: number) {
        return axiosInstance.delete(`/devices/${id}`)
    },

    async toggleDevice(id: number, status: boolean) {
        return axiosInstance.put(`/devices/${id}/status`, { status })
    }
}

export const taskService = {
    async getAllTasks() {
        return axiosInstance.get('/tasks')
    },

    async addTask(task: Omit<Task, 'id'>) {
        return axiosInstance.post('/tasks', task)
    },

    async updateTask(id: number, task: Partial<Task>) {
        return axiosInstance.put(`/tasks/${id}`, task)
    },

    async deleteTask(id: number) {
        return axiosInstance.delete(`/tasks/${id}`)
    }
}

export const dashboardService = {
    async getDashboardStats() {
        return axiosInstance.get('/dashboard/stats')
    },

    async getRecentDevices() {
        return axiosInstance.get('/dashboard/recent-devices')
    }
} 